//
//  CheckValuationController.m
//  New_Runway
//
//  Created by mack on 2018/2/12.
//  Copyright © 2018年 NelsonJ. All rights reserved.
//

#import "CheckValuationController.h"

@interface CheckValuationController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIActionSheetDelegate>
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topDis;
@property (weak, nonatomic) IBOutlet UITextField *ValueTF;
@property (weak, nonatomic) IBOutlet UIButton *updataImage;
@property (weak, nonatomic) IBOutlet UIButton *saveBtn;
@property (weak, nonatomic) IBOutlet UIButton *cancelBtn;
@property (nonatomic, strong) NSData *imageData;
@property (weak, nonatomic) IBOutlet UIImageView *checkIm;
@property (weak, nonatomic) IBOutlet UITextField *checkResult;
@property (weak, nonatomic) IBOutlet UITextView *remark;

@end

@implementation CheckValuationController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationBarView.titleLabel.text = @"检测估值";
    self.view.backgroundColor = UIColorHex(0xf5f5f5);
    self.ValueTF.keyboardType = UIKeyboardTypeDecimalPad;
    [self.ValueTF becomeFirstResponder];
    self.saveBtn.layer.masksToBounds = YES;
    self.saveBtn.layer.cornerRadius = 5;
    self.cancelBtn.layer.masksToBounds = YES;
    self.cancelBtn.layer.cornerRadius = 5;
    self.cancelBtn.layer.borderColor = MAIN_NAV_COLOR().CGColor;
    self.cancelBtn.layer.borderWidth = 0.5f;
    self.topDis.constant = self.navH;
    self.ValueTF.tintColor = MAIN_NAV_COLOR();
    self.checkResult.tintColor = self.remark.tintColor = MAIN_NAV_COLOR();
    self.remark.layer.masksToBounds = YES;
    self.remark.layer.borderColor = UIColorHex(0xcccccc).CGColor;
    self.remark.layer.borderWidth = 0.5f;
    self.remark.layer.cornerRadius = 5;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(priceTextDidChange:) name:UITextFieldTextDidChangeNotification object:self.ValueTF];
    
}
- (IBAction)updataImageClick:(id)sender {
    
    [self editPeopleMessage];
    
}
- (IBAction)saveBtnClick:(id)sender {
    [self.ValueTF resignFirstResponder];
    
    [self updataCheckReport];
    
}
- (IBAction)cancelBtnClick:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)updataCheckReport{
    
    if ([self.ValueTF.text isEqualToString:@""]) {
        [ShowMessage showHintMessage:@"请输入估值金额!" duration:2.0 withRemindId:remindWarning];
        return;
    }
    
    if ([self.ValueTF.text floatValue] > 9999.99) {
        [ShowMessage showHintMessage:@"估值金额上限9999.99万元!" duration:2.0 withRemindId:remindWarning];
        return;
    }
    
    NSString *url = [NSString stringWithFormat:@"%@%@",Api,checkReportApi];
    NSDictionary *dic = @{
                          @"carId":self.carId,
                          @"detectUserId":[NRWCarUser sharedUser].userId,
                          @"detectionId":self.detectionId,
                          @"detectionPrice":[NSString stringWithFormat:@"%.2f", self.ValueTF.text.floatValue],
                          @"detectionResult":self.checkResult.text,
                          @"detectionRemark":self.remark.text
                          
                          };
    if (!self.imageData) {
        [ShowMessage showHintMessage:@"请输上传报告单!" duration:2.0 withRemindId:remindWarning];
        return;
    }
    
   
    [YQNetworking uploadFileWithUrl:url params:dic fileData:self.imageData type:@"jpg" name:@"uploadFile" mimeType:@"image/*" progressBlock:^(int64_t bytesWritten, int64_t totalBytes) {
        
    } successBlock:^(id response) {
        
        if ([response[@"code"] isEqual:@1]) {
            [ShowMessage showHintMessage:@"复检成功" duration:2.0 withRemindId:remindSuccess];
            
            [self checkVCReloadData];

            [self.navigationController popViewControllerAnimated:YES];
            
        }else{
            [ShowMessage showHintMessage:response[@"msg"] duration:2.0 withRemindId:remindFail];

        }
        
    } failBlock:^(NSError *error) {
        [ShowMessage showHintMessage:@"请求失败!" duration:2.0 withRemindId:remindFail];
    }];
}

- (void)checkVCReloadData {
    
    UIViewController *vc = self.navigationController.viewControllers[self.navigationController.viewControllers.count - 2];
    
    if ([vc isKindOfClass:NSClassFromString(@"UndetectedWorkListVC")]) {
        
        [vc performSelector:NSSelectorFromString(@"reloadData")];
    }
}


- (void)priceTextDidChange:(NSNotification *)notification {
    
    if ([notification.object isKindOfClass:[UITextField class]]) {
        
        UITextField *textField = (UITextField *)notification.object;
        
        textField.text = [textField.text returnRealPrice];
    }
}

- (void)editPeopleMessage{
    
    UIActionSheet *sheet;
    
    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        sheet  = [[UIActionSheet alloc] initWithTitle:@"选择图像" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照", @"从相册选择", nil];
    }
    else {
        sheet = [[UIActionSheet alloc] initWithTitle:@"选择图像" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"从相册选择", nil];
    }
    
    
    [sheet showInView:self.view];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSUInteger sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        switch (buttonIndex) {
                
            case 0: //相机
                sourceType = UIImagePickerControllerSourceTypeCamera;
                break;
            case 1: //相册
                sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                break;
            case 2:
                return;
                break;
        }
    }
    else {
        switch (buttonIndex) {
            case 0:
                sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
                
                break;
            case 1:
                return;
                break;
                
        }
        
        
        
    }
    // 跳转到相机或相册页面
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    imagePickerController.sourceType = sourceType;
    
    [self presentViewController:imagePickerController animated:YES completion:^{}];
    
    
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{}];
    
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    self.checkIm.image = image;
    NSData *data = [UIImage reSizeImageData:image maxImageSize:375 maxSizeWithKB:1024];

    self.imageData = data;
    
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];//关闭键盘
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
